package com.app.adnroid.sichuanxiaoke.cn.xiaokebusiness.activity;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.app.adnroid.sichuanxiaoke.cn.xiaokebusiness.R;
import com.app.adnroid.sichuanxiaoke.cn.xiaokebusiness.Utils.Constant;
import com.app.adnroid.sichuanxiaoke.cn.xiaokebusiness.Utils.LogUtil;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpHeaders;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class IntelligenceDoorManageActivity extends AppCompatActivity {
    @BindView(R.id.tb)
    Toolbar tb;



    private String refresh_token;
    private String access_token;
    private String deviceCode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_intelligence_door_manage);
        ButterKnife.bind(this);
        initUI();
        getCredential();
    }

    private void initUI() {
        setSupportActionBar(tb);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        tb.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }
    @OnClick({R.id.farOpenDoor,R.id.OpenDoorPassword,R.id.locationManage})
    public  void OnClick(View view){
        if(refresh_token == null || access_token == null || deviceCode == null){
            Toast.makeText(this,"门锁数据初始化失败",Toast.LENGTH_SHORT).show();
            return;
        }

        switch (view.getId()){
            case R.id.farOpenDoor:
                FarOpenDoor();
                break;
            case R.id.OpenDoorPassword:
                OpenDoorPassword();
            break;
            case R.id.locationManage:
                startActivity(new Intent(this,CreateBaiduMapFenceActivity.class));
                break;
        }
    }

    private void FarOpenDoor(){
        SendOpenDoorOrder();
    }

    private void OpenDoorPassword(){
        SendOpenDoorPasswordOrder();
    }

    private void SendOpenDoorPasswordOrder(){
        String startDataTime = getDataTime(0);
        String endDateTime = getDataTime(300*1000); //设置有效时间为5分钟
        int  identity =(int) (Math.random() * 100);

        JSONObject data = new JSONObject();
        try {
            data.put("DeviceCode",deviceCode);
            data.put("StartDateTime",startDataTime);
            data.put("EndDateTime",endDateTime);
            data.put("PwdType","2");//1、一次性密码，有效期内一次输入成功后作废 2、时段性密码，有效期内可多次输入
            data.put("PwdGroup"," 1");
            data.put("Identity",identity);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        HttpHeaders headers = new HttpHeaders();
        headers.put("Authorization",getHeaderParams());
        LogUtil.i("getNetWork","--pass---onSuccess-------"+data.toString());
        OkGo.<String>post(Constant.GET_PASSWORD_URL).headers(headers).upJson(data).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                String body = response.body();
                LogUtil.i("getNetWork","--pass---onSuccess-------"+body);
            }

            @Override
            public void onError(Response<String> response) {

                String body = response.body();
                LogUtil.i("getNetWork","--pass---onError-------"+body+"---error--"+response.getException());
            }
        });
    }

    private void getCredential() {
        HttpParams httpParams = new HttpParams();
        httpParams.put("username","100215NSHXEBGR");
        httpParams.put("password","50482e8f");
        httpParams.put("grant_type","password");

        OkGo.<String>post(Constant.CREDENTIAL_URL).params(httpParams).execute(new StringCallback() {



            @Override
            public void onSuccess(Response<String> response) {
                String body = response.body();
                LogUtil.i("getNetWork","-----onSuccess-------"+body);
                try {
                    JSONObject jsonObject = new JSONObject(body);
                    access_token = jsonObject.optString("access_token");
                    refresh_token = jsonObject.optString("refresh_token");

                } catch (JSONException e) {
                    Toast.makeText(IntelligenceDoorManageActivity.this,"获取凭证失败",Toast.LENGTH_SHORT).show();

                }

                getDeviceList();

            }
        });
    }
    private void reRefresh() {
        HttpParams httpParams = new HttpParams();
        httpParams.put("refresh_token",refresh_token);
        httpParams.put("grant_type","refresh_token");

        OkGo.<String>post(Constant.REFRESH_URL).params(httpParams).execute(new StringCallback() {



            @Override
            public void onSuccess(Response<String> response) {
                String body = response.body();
                LogUtil.i("getNetWork","-----onSuccess-------"+body);
                try {
                    JSONObject jsonObject = new JSONObject(body);
                    access_token = jsonObject.optString("access_token");
                    refresh_token = jsonObject.optString("refresh_token");
                } catch (JSONException e) {
                    Toast.makeText(IntelligenceDoorManageActivity.this,"刷新凭证失败",Toast.LENGTH_SHORT).show();

                }

            }
        });
    }
    private void getDeviceList() {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.put("Authorization",getHeaderParams());
        OkGo.<String>get(Constant.GET_DEVICE_LIST_URL).headers(httpHeaders).execute(new StringCallback() {

            @Override
            public void onSuccess(Response<String> response) {
                String body = response.body();
                LogUtil.i("getNetWork","-----onSuccess-------"+body);
                try {
                    JSONObject jsonObject = new JSONObject(body);
                    JSONArray value = jsonObject.optJSONArray("value");
                    if(value.length() == 0||value == null){
                        return;
                    }
                    deviceCode = value.getJSONObject(0).optString("DeviceCode");

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                //SendOpenDoorOrder();

            }
        });
    }
    private void SendOpenDoorOrder() {
        int  identity =(int) (Math.random() * 100);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.put("Authorization",getHeaderParams());
        if(deviceCode.isEmpty()){
            Toast.makeText(this,"请先获取设备列表",Toast.LENGTH_SHORT).show();
            return;
        }

        JSONObject object = new JSONObject();
        try {
            object.put("DeviceCode",deviceCode);
            object.put("Identity",identity);
        } catch (JSONException e) {
            e.printStackTrace();
        }


        OkGo.<String>post(Constant.OPEN_DOOR_URL).headers(httpHeaders).upJson(object).execute(new StringCallback() {



            @Override
            public void onSuccess(Response<String> response) {
                String body = response.body();
                LogUtil.i("getNetWork","-----onSuccess-------"+body);
                try {
                    JSONObject jsonObject = new JSONObject(body);
                    String value = jsonObject.optString("value");
                    if(value.equals("0")){
                        Toast.makeText(IntelligenceDoorManageActivity.this,"开门成功",Toast.LENGTH_SHORT).show();
                    }else {
                        Toast.makeText(IntelligenceDoorManageActivity.this,"开门失败",Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    Toast.makeText(IntelligenceDoorManageActivity.this,"刷新凭证失败",Toast.LENGTH_SHORT).show();

                }

            }
        });
    }

    private String getHeaderParams(){

        return "bearer"+" "+access_token;
    }

    private String getDataTime(long differ){
        long timeMillis = System.currentTimeMillis()+differ;
        Date date=new Date();
        date.setTime(timeMillis);
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//24小时制 yyyy-MM-dd hh-mm-ss 12小时制
        String timeformat = simpleDateFormat.format(date);
        LogUtil.i("timeformat","----时间格式化------"+timeformat);
        return timeformat;
    }


}
